﻿using Frame.Core.IServices.Admin;
using Frame.Core.Models;
using Frame.Core.Repository;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Frame.Core.Services.Admin
{
    public class MenuService : BaseService<Menus>, IMenuService
    {
        readonly IRepositoryBase<Menus> _dal;
        readonly IRepositoryBase<Powers> _powerRepository;

        public MenuService(IRepositoryBase<Menus> dal, IRepositoryBase<Powers> powerRepository)
        {
            this._dal = dal;
            base.BaseDal = dal;
            _powerRepository = powerRepository;
        }
        public async Task<List<Menus>> GetMenusAsync()
        {
            List<Menus> menus = new List<Menus>();
            List<Menus> dbMenus = await _dal.Select.Include(a => a.Powers).OrderBy(o=>o.SortIndex).ToListAsync();
            ResolveMenuCollection(menus,dbMenus, 0, 0);

            return menus;
        }


        private int ResolveMenuCollection(List<Menus> menus, List<Menus> dbMenus, int? parentMenuId, int level)
        {
            int count = 0;

            foreach (var menu in dbMenus.Where(m => m.ParentID == parentMenuId))
            {
                count++;

                menus.Add(menu);
                menu.TreeLevel = level;
                menu.IsTreeLeaf = true;
                menu.Enabled = true;

                level++;
                int childCount = ResolveMenuCollection(menus,dbMenus, menu.ID, level);
                if (childCount != 0)
                {
                    menu.IsTreeLeaf = false;
                }
                level--;
            }

            return count;
        }

        public async Task<long> GetMenuParentIDCountById(int parentID)
        {
            return await _dal.Select.Where(a => a.ParentID == parentID).CountAsync();
        }
        public async Task<long> GetPowerMenusIdCountById(int MenusId)
        {
            return await _powerRepository.Select.Where(a => a.MenusId == MenusId).CountAsync();
        }
    }
}
